class CommentsController < ApplicationController
  before_filter :require_admin, :except => :create
  before_filter :find_or_initialize_comment,:except => [:index, :create]
  # after_filter :expire_fragment_cache, :only => [:create, :update, :destroy]
  # GET /comments
  # GET /comments.xml
  def index
    @comments = Comment.all

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @comments }
    end
  end

  # GET /comments/1
  # GET /comments/1.xml
  def show
    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @comment }
    end
  end

  # GET /comments/new
  # GET /comments/new.xml
  def new
    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @comment }
    end
  end

  # GET /comments/1/edit
  def edit
  end

  # POST /comments
  # POST /comments.xml
  def create
    @comment = Comment.new(params[:comment])
    @comment.ip = request.remote_ip
    respond_to do |format|
      if @comment.save
        format.html { redirect_to(@comment.post, :notice => '发表评论成功!') }
        format.xml  { render :xml => @comment, :status => :created, :location => @comment }
      else
        format.html { redirect_to(@comment.post, :notice => '发表评论失败!') }
        format.xml  { render :xml => @comment.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /comments/1
  # PUT /comments/1.xml
  def update
    respond_to do |format|
      if @comment.update_attributes(params[:comment])
        format.html { redirect_to(comments_url, :notice => '评论编辑成功!') }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @comment.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /comments/1
  # DELETE /comments/1.xml
  def destroy
    @comment.destroy

    respond_to do |format|
      format.html { redirect_to(comments_url) }
      format.xml  { head :ok }
    end
  end

  private
  def find_or_initialize_comment
    @category = params[:id] ? Comment.find(params[:id]) : Comment.new
  end
  # => 清除右侧目录树片段的缓存
  def expire_fragment_cache
    expire_fragment(RecordSweeper::PATH.merge(:action_suffix => 'recent_comments'))
  end
end
